package com.dimao.certificate_build_service.pdf;

import com.dimao.certificate_build_service.Util.StrUtil;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.kernel.font.PdfFont;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

import java.util.List;
import java.util.Map;

public abstract class Value implements Assignable {
    @Override
    public void setValue(Map<String, PdfFormField> formMap, List<PdfFont> fonts, JsonObject jsonObject) {
        JsonArray jsonArray = jsonObject.getJsonArray("students");

        PdfFont fontOne = fonts.get(0);
        PdfFont fontTwo = fonts.get(1);

        formMap.get("code")
                .setValue(jsonObject.getString("code"), fontOne, 13.0f);
        formMap.get("number")
                .setValue(jsonObject.getString("number"), fontTwo, 30.0f);

        String endOfStudents = additionalOperating(formMap, fonts, jsonObject);

        List<String> split = StrUtil.outOfLimit(jsonObject.getString("content"), 28);
        if(split.size() >= 3) {
            StringBuilder builderLineTwo = new StringBuilder(split.get(1));
            StringBuilder builderLineThree = new StringBuilder(split.get(2));

            builderLineTwo.insert(builderLineTwo.length(), builderLineThree.substring(0, 2));
            builderLineThree.delete(0, 2);
            split.set(1, builderLineTwo.toString());
            split.set(2, builderLineThree.toString());
        }

        for(int i = 0; i < split.size(); i++){
            String key = "content" + (i + 1);
            formMap.get(key)
                    .setValue(split.get(i), fontOne, 20.0f);
        }

        for(int i = 0; i < (jsonArray.size() - 1); i++){
            String key = "name" + (i + 1);
            String lineBreakKey = key + "_e";
            String value = addSpaceToFourUtf8Chars(jsonArray.getString(i));
            if(formMap.containsKey(lineBreakKey)) formMap.get(lineBreakKey)
                    .setValue(value, fontTwo, 19.0f);
            else formMap.get(key)
                    .setValue(value + "、", fontTwo, 19.0f);
        }

        String key = "name" + jsonArray.size();
        String value = addSpaceToFourUtf8Chars(jsonArray.getString(jsonArray.size() - 1)) + endOfStudents;
        formMap.get(key).setValue(value, fontTwo, 19.0f);
    }

    protected abstract String additionalOperating(Map<String, PdfFormField> formMap, List<PdfFont> fonts, JsonObject jsonObject);

    protected static String addSpaceToFourUtf8Chars(String name) {
        switch (name.length()){
            case 3 : return new StringBuilder(name)
                    .insert(1, " ")
                    .insert(3, " ")
                    .toString();
            case 2 : return new StringBuilder(name)
                    .insert(1, "     ")
                    .toString();
            default: return name;
        }
    }
}
